package org.apache.flink.runtime.metrics.groups;

import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.ConsumerID;
import org.apache.flink.metrics.CharacterFilter;
import org.apache.flink.runtime.metrics.MetricRegistry;
import org.apache.flink.runtime.metrics.dump.QueryScopeInfo;
import org.apache.flink.runtime.metrics.scope.ScopeFormat;

import javax.annotation.Nullable;

import java.util.Map;

/**
 * Special abstract {@link org.apache.flink.metrics.MetricGroup} representing everything belonging
 * to a specific consumer.
 *
 * @param <C> The type of the parent ComponentMetricGroup.
 */
@Internal
public abstract class ConsumerMetricGroup<C extends ComponentMetricGroup<C>>
        extends ComponentMetricGroup<C> {

    /** The ID of the job represented by this metrics group. */
    protected final ConsumerID consumerId;

    /** The name of the job represented by this metrics group. */
    @Nullable protected final String consumerName;

    // ------------------------------------------------------------------------

    protected ConsumerMetricGroup(
            MetricRegistry registry,
            C parent,
            ConsumerID consumerId,
            @Nullable String consumerName,
            String[] scope) {
        super(registry, scope, parent);

        this.consumerId = consumerId;
        this.consumerName = consumerName;
    }

    public ConsumerID jobId() {
        return consumerId;
    }

    @Nullable
    public String consumerName() {
        return consumerName;
    }

    @Override
    protected QueryScopeInfo.ConsumerQueryScopeInfo createQueryServiceMetricInfo(
            CharacterFilter filter) {
        return new QueryScopeInfo.ConsumerQueryScopeInfo(this.consumerId.toString());
    }

    // ------------------------------------------------------------------------
    //  Component Metric Group Specifics
    // ------------------------------------------------------------------------

    @Override
    protected void putVariables(Map<String, String> variables) {
        variables.put(ScopeFormat.SCOPE_JOB_ID, consumerId.toString());
        variables.put(ScopeFormat.SCOPE_JOB_NAME, consumerName);
    }

    @Override
    protected String getGroupName(CharacterFilter filter) {
        return "consumer";
    }
}
